package com.augurit.agmobile.agwater5.drainage.supervise.view

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.graphics.toColorInt
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.augurit.agmobile.agwater5.drainage.common.constant.StringConstant
import com.augurit.agmobile.agwater5.drainage.common.ex.launchActivity
import com.augurit.agmobile.agwater5.drainage.common.tabview.TabLayoutHelper
import com.augurit.agmobile.agwater5.drainage.supervise.model.SuperviseRole
import com.augurit.agmobile.agwater5.drainage.supervise.model.SuperviseType
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.arm.base.BaseActivity
import com.example.arm.ext.dpInt
import com.example.arm.ext.toast
import com.example.arm.http.imageloader.ImageLoader
import com.example.drainage.R
import com.example.drainage.base.ktexpand.setBackgroundByDrawable
import com.example.drainage.base.ktexpand.visible
import com.example.drainage.databinding.ActivitySuperviseSignBinding
import com.example.drainage.http.imageloader.ImageConfigImpl
import com.example.drainage.http.imageloader.ImageConfigImplBuilder
import com.google.android.material.tabs.TabLayout
import org.kodein.di.instance

/**
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.augurit.agmobile.agwater5.drainage.supervise.view
 * @createTime 创建时间 ：2022/1/4
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
class SuperviseSignActivity : BaseActivity<ActivitySuperviseSignBinding>() {

    private var facilityType: SuperviseType = SuperviseType.Reservoir

    private var role: SuperviseRole = SuperviseRole.TeamMembers

    private var id: String? = null

    private val mImageLoader: ImageLoader<ImageConfigImpl> by instance()

    private val adapter: SignAdapter by lazy {
        SignAdapter(mImageLoader)
    }

    companion object {
        fun jump(activity: Activity, facilityType: SuperviseType, id: String, role: SuperviseRole) {
            activity.launchActivity<SuperviseSignActivity> {
                putExtra(StringConstant.KEY_TYPE, facilityType)
                putExtra(StringConstant.KEY_ID, id)
                putExtra(StringConstant.KEY_PERSON, role)
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?): ActivitySuperviseSignBinding {
        return ActivitySuperviseSignBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        initIntent()
        initView()
        initViewModel()
        initData()
    }

    //-----------------已定义方法---------------------------
    private fun initIntent() {
        if (intent.hasExtra(StringConstant.KEY_TYPE)) {
            facilityType = intent.getSerializableExtra(StringConstant.KEY_TYPE) as SuperviseType
        }
        if (intent.hasExtra(StringConstant.KEY_ID)) {
            id = intent.getStringExtra(StringConstant.KEY_ID)
        }
        if (intent.hasExtra(StringConstant.KEY_PERSON)) {
            role = intent.getSerializableExtra(StringConstant.KEY_PERSON) as SuperviseRole
        }
    }

    private fun initView() {
//        immersionStatusBar()
//        mBinding.apply {
//            titlebar.setTitle(facilityType.typeName)
//                .setTitleTextColor("#222222".toColor())
//                .setTitleTextSize(18f)
//                .setLeftImageIcon(R.mipmap.back_arrow, 14)
//                .setLeftImageTint("#222222".toColor())
//                .setLeftImageClick { finish() }
//                .setImmersion(true)
//                .setBackgroundResource(R.color.white)
//
//        }
        binding.apply {
            tvClearSign.setBackgroundByDrawable(3.dpInt, fillColor = "#FFE8F1FF".toColorInt())
            tvSaveSign.setBackgroundByDrawable(3.dpInt, fillColor = "#FFE8F1FF".toColorInt())
            val tabList = when (role) {
                SuperviseRole.GroupLeader -> listOf("检查组长", "管理单位", "检查组员")
                SuperviseRole.TeamMembers -> listOf("检查组员")
            }
            TabLayoutHelper.addTabs(tabLayout, -1, -1, -1, tabList)
            tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if (tab != null) {
                        signView.reset()
                        if (role == SuperviseRole.GroupLeader && tab.position == 2) {
                            frameSignContent.visible = false
                            tvSignTips.visible = false
                        } else {
                            frameSignContent.visible = true
                            tvSignTips.visible = true
                        }
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }
            })

            adapter.onDeleteListener = {

            }
            signRecyclerView.adapter = adapter
            signRecyclerView.layoutManager = LinearLayoutManager(this@SuperviseSignActivity, RecyclerView.HORIZONTAL, false)

            tvClearSign.setOnClickListener {
                signView.reset()
            }
            tvSaveSign.setOnClickListener {
                if (!signView.checkLineCount(1)) {
                    toast("请签名后点击保存按钮!")
                    return@setOnClickListener
                } else if (role == SuperviseRole.TeamMembers && adapter.itemCount >= 3) {
                    toast("组员最多签三个名字!")
                    return@setOnClickListener
                } else if (role == SuperviseRole.GroupLeader && adapter.itemCount >= 1) {
                    toast("最多签一个名字!")
                    return@setOnClickListener
                }
                signView.saveImgToLocal(getSignKey()) { isSuccess, filePath ->
                    if (isSuccess) {
                        adapter.addData(SignBean(filePath!!))
                        signView.reset()
                    } else {
                        Toast.makeText(this@SuperviseSignActivity, "保存失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
            tvFinish.setOnClickListener {
                finish()
            }
        }
    }

    private fun initViewModel() {

    }

    private fun initData() {

    }

    private fun getSignKey(): String {
        return when (role) {
            SuperviseRole.GroupLeader -> {
                if (binding.tabLayout.getTabAt(0)?.isSelected == true) {
                    "GroupLeader"
                } else {
                    "AdminDepartment"
                }
            }
            SuperviseRole.TeamMembers -> {
                "TeamMembers"
            }
        }
    }

    data class SignBean(val url: String, val bean: Any? = null)

    class SignAdapter(private val mImageLoader: ImageLoader<ImageConfigImpl>) :
        BaseQuickAdapter<SignBean, BaseViewHolder>(R.layout.item_supervise_sign) {

        var onDeleteListener: ((SignBean) -> Unit)? = null

        var isShowDelete = true

        override fun convert(holder: BaseViewHolder, item: SignBean) {
            mImageLoader.loadImage(context, ImageConfigImplBuilder {
                url = item.url
                imageView = holder.getView(R.id.ivPic)
            })
            holder.getView<View>(R.id.ivDel).apply {
                isVisible = isShowDelete
                if (isShowDelete) {
                    setOnClickListener {
                        onDeleteListener?.invoke(getItem(holder.absoluteAdapterPosition))
                        removeAt(holder.absoluteAdapterPosition)
                    }
                }
            }
        }
    }
}